# coding:utf8
import requests
import re
import time
import pycurl
import StringIO
import random
from pymongo import MongoClient
from ipexception import IPException

from config.glob_conf import PROXY_HOST

conn = MongoClient(PROXY_HOST)
db = conn['crawler_proxy']
collection_proxy = db['proxy']


def get_value_ip():
    total_count = collection_proxy.count()
    index = random.randint(0, total_count - 1)
    ip = collection_proxy.find_one({}, skip=index, limit=1)
    ip = ip.get('_id')
    return {'http': u'http://' + ip}


def test_ip():
    MAX_TIME = 20
    a_time = MAX_TIME
    while a_time > 0:
        proxy = get_value_ip()
        print proxy
        try:
            response = requests.get(url='http://218.57.139.24/', proxies=proxy, timeout=5)
            if response.status_code != 200:
                a_time -= 1
                continue
            print response.status_code
            response.close()
            return proxy
        except Exception, e:
            print e
            continue
    raise IPException("change IP")


# def test_ip():
#     import requests
#     while True:
#         proxy = get_value_ip()
#         print proxy
#         try:
#             response = requests.get(url='http://218.57.139.24/',proxies=proxy,timeout=5)
#             if response.status_code!=200:
#                 continue
#             print response.status_code
#             return proxy
#         except Exception,e:
#             print e
#             continue


if __name__ == "__main__":
    test_ip = test_ip()
    print test_ip

    # test_ip()
